package com.serkol.ams.controller.api;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.serkol.ams.bean.MyPageOld;
import com.serkol.ams.bean.Result;
import com.serkol.ams.entity.CloudInventory;
import com.serkol.ams.entity.CloudOrderDetail;
import com.serkol.ams.entity.CloudOrderMaster;
import com.serkol.ams.entity.LoginLog;
import com.serkol.ams.service.AgentInvitationRelationshipService;
import com.serkol.ams.service.CloudInventoryService;
import com.serkol.ams.service.CloudOrderDetailService;
import com.serkol.ams.service.CloudOrderMasterService;
import com.serkol.annotation.IsLogin;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultCode;
import com.serkol.constant.ResultConstant;
import com.serkol.exception.AuthException;
import com.serkol.utils.OrderUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/cloud/order")
public class CloudOrderApiController {
    @Autowired
    private CloudOrderMasterService masterService;
    @Autowired
    private CloudOrderDetailService detailService;

    @Autowired
    private CloudInventoryService cloudInventoryService;

    @Autowired
    private AgentInvitationRelationshipService agentInvitationRelationshipService;
    @Value("${upload.host}")
    private String uploadhost;
    @IsLogin
    @Transactional
    @PostMapping("/createOrder")
    public Result createOrder(@RequestBody JSONObject object) throws AuthException {
        LoginLog loginLog = AuthConstant.getLoginLog();
        boolean save = false;
        CloudOrderMaster order = object.getObject("order", CloudOrderMaster.class);
        order.setSn(OrderUtils.getOrderNum(loginLog.getUserId()));
        order.setUserId(loginLog.getUserId());
        order.setOperatorId(loginLog.getUserId());

        JSONArray details = object.getJSONArray("details");
        List<CloudOrderDetail> orderDetails = details.toJavaList(CloudOrderDetail.class);
        save = masterService.save(order);
        if (save) {
            List<CloudOrderDetail> orderDetailsN = new ArrayList<>();

            Iterator<CloudOrderDetail> iterator = orderDetails.iterator();
            while (iterator.hasNext()) {
                CloudOrderDetail next = iterator.next();
                next.setConsignerId(loginLog.getUserId());
                next.setOrderId(order.getId());
                next.setUserId(order.getUserId());
                next.setAddressId(order.getAddressId());
                orderDetailsN.add(next);
                CloudInventory inventory=new CloudInventory();
                inventory.setQuantity(next.getQuantity());
                inventory.setGoodsId(next.getGoodsId());
                inventory.setId(next.getCloudId());
                inventory.setUserId(order.getUserId());
                cloudInventoryService.updateOrder(inventory);

            }
            boolean b = detailService.saveBatch(orderDetailsN);
            if (b) {
                return Result.ok();
            } else {
                throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
            }
        } else {
            throw new AuthException(ResultCode.REQUEST_ERROR_PAYMENT_REQUIRED);
        }

    }

    @IsLogin
    @GetMapping("/findByPageList")
    public Result findByPageList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current
            , @RequestParam(name = "consignerName", defaultValue = "") String consignerName
            , @RequestParam(name = "userName", defaultValue = "") String userName
            , @RequestParam(name = "sn", defaultValue = "") String sn
            , @RequestParam(name = "partySn", defaultValue = "") String partySn) {

        //paymentMethod,paymentStatus,userName,sn,partySn,date

        Result result = new Result();
      return masterService.findByPageList(pageSize,current, consignerName, userName, sn, partySn);

    }
    @IsLogin
    @GetMapping("/findByOrderDetailList")
    public Result findByOrderDetailList(
            @RequestParam(name = "orderId", defaultValue = "0") long orderId) {
        Result result = new Result();
        List<Map<String, Object>> list = detailService.findByOrderDetailList(orderId);
        if (list.size() > 0) {
            result.setStatus(ResultConstant.SUCSESS);
            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }
        return result;
    }
    @GetMapping("/findByMyList")
    public Result findByMyList(@RequestParam(name = "status", defaultValue = "0") int status) {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();
        List<Map<String, Object>> list = masterService.findByMyList(status);
        if (list.size() > 0) {
            result.setStatus(ResultConstant.SUCSESS);
            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }
        return result;
    }

    @IsLogin
    @PostMapping("/shipments")
    public Result shipments(
            @RequestParam(name = "orderId", defaultValue = "0") long orderId,
            @RequestParam(name = "postNUm", defaultValue = "") String postNUm) {
        LoginLog loginLog = AuthConstant.getLoginLog();

        CloudOrderMaster orderMaster = new CloudOrderMaster();
        orderMaster.setId(orderId);
        //orderMaster.setIsPay(0);
        //  orderMaster.setPaymentDate(new Date());
        // orderMaster.setPaymentMethod(6);
        //   orderMaster.setPaymentStatus(3);
        if (StringUtils.isNotEmpty(postNUm)) {
            orderMaster.setPostNum(postNUm);
        }
        orderMaster.setStatus(2);
        orderMaster.setOperatorId(loginLog.getUserId());
        boolean b = masterService.updateById(orderMaster);
        if (b) {
            return Result.ok();
        } else {
            return Result.failure();
        }

    }


    @IsLogin
    @PostMapping("/adminPayment")
    public Result adminPayment(
            @RequestParam(name = "orderId", defaultValue = "0") long orderId) {
        LoginLog loginLog = AuthConstant.getLoginLog();

        CloudOrderMaster orderMaster = new CloudOrderMaster();
        orderMaster.setId(orderId);
        orderMaster.setStatus(2);
        orderMaster.setOperatorId(loginLog.getUserId());
        boolean b = masterService.updateById(orderMaster);
        if (b) {
            return Result.ok();
        } else {
            return Result.failure();
        }

    }
    @IsLogin
    @PostMapping("/cancelOrder")
    public Result cancelOrder(
            @RequestParam(name = "orderId", defaultValue = "0") long orderId) {
        LoginLog loginLog = AuthConstant.getLoginLog();

        CloudOrderMaster orderMaster = new CloudOrderMaster();
        orderMaster.setId(orderId);
        //orderMaster.setIsPay(0);
        //  orderMaster.setPaymentDate(new Date());
        // orderMaster.setPaymentMethod(6);
        orderMaster.setStatus(3);
        orderMaster.setOperatorId(loginLog.getUserId());
        boolean b = masterService.updateById(orderMaster);
        if (b) {
            return Result.ok();
        } else {
            return Result.failure();
        }

    }


    @IsLogin
    @PostMapping("/edit")
    public Result edit(@RequestBody JSONObject data) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        JSONArray goods = data.getJSONArray("goods");
        List<CloudOrderDetail> detailList = goods.toJavaList(CloudOrderDetail.class);
        CloudOrderMaster master = data.toJavaObject(CloudOrderMaster.class);
        master.setOperatorId(loginLog.getUserId());
        boolean byId = false;
        if(master.getPrice().intValue()>0) {
            if (master.getId() != null && master.getId() > 0) {
                byId = masterService.updateById(master);
            } else {
                byId = masterService.save(master);
            }
            if (byId) {
                for (int i = 0; i < detailList.size(); i++) {
                    CloudOrderDetail taocanDetail = detailList.get(i);

                    taocanDetail.setOrderId(master.getId());

                    detailList.set(i, taocanDetail);
                }
                boolean b = detailService.saveOrUpdateBatch(detailList);
                return b ? Result.ok() : Result.failure();
            } else {
                return Result.failure();
            }
        }else {
            return Result.failure();
        }


    }

    @IsLogin
    @GetMapping("/findGoodsList")
    public Result findGoodsList(
                                @RequestParam(name = "agentId", defaultValue = "0") long agentId) {
        List<Map<String, Object>> data = detailService.findGoodsList( agentId);
        return Result.ok(data);
    }

    @IsLogin
    @GetMapping("/info")
    @ResponseBody
    public Result info(@RequestParam(name = "id", defaultValue = "0") long id) {
        AuthConstant.setPathUrl(uploadhost);
        Map<String, Object> info = masterService.info(id);

        return Result.ok(info);
    }

}
